(ns admin-framework.transaction
  (:gen-class
   :extends org.jboss.netty.channel.SimpleChannelHandler
   :init init
   :state authenticated)
  (:use [cheshire.core]
        [cheshire.factory])
  (:require [clojure.contrib.sql :as sql])
  (:import org.jboss.netty.channel.SimpleChannelHandler))

(def host "localhost")
(def port "3306")
(def db-name "salesys")

(def db {:classname "com.mysql.jdbc.Driver"
         :subprotocol "mysql"
         :subname (str "//" host ":" port "/" db-name)
         :user "zdc"
         :password "zdc"
         })

(defn -init []
  [[] (atom false)])

(defn get-buf-str [buf]
  (.toString buf (java.nio.charset.Charset/forName "UTF-8")))

;;authenticate
(defn -auth [this uname pwd]
  (when-not (.authenticated this)
    (sql/with-connection
      (println "connect !" (.authenticated this)))))

(defmulti call-rpc (fn [id] id))

(defmethod call-rpc 1 [ch jsdata]
  (println "this is 1"))

(defmethod call-rpc 2 [ch jsdata]
  (println "this is 2"))

(defn -messageReceived [ctx msg]
  (let [buf (.getMessage msg)
        utf (get-buf-str [buf])
        data (parse-string utf)]
    (call-rpc data)))

(defn get-buf-str [buf]
  (.toString buf (java.nio.charset.Charset/forName "UTF-8")))

(defmulti call-rpc (fn [ch jsdata & arg] (jsdata "id")))

(defmethod call-rpc 1 [ch jsdata]
  (println "this is 1"))

(defmethod call-rpc 2 [ch jsdata]
  (println "this is 2"))

(defn -messageReceived [this ctx msg]
   (let [buf (.getMessage msg)
                utf  (get-buf-str buf)
         data (parse-string utf)]
     (.auth this)
     (call-rpc (.getChannel msg) data)))

(defn -exceptionCaught [this ctx e]
  (println "catch exception" e))

(defn -channelClosed [this ctx e]
  (println "Channel closed" e))

(defn -channelConnected [this ctx e]
  (println "Channel connected" e))

